package com.zbcz.erp.activity

import android.graphics.Bitmap
import android.graphics.pdf.PdfRenderer
import android.net.Uri
import android.os.Bundle
import android.os.ParcelFileDescriptor
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.zbcz.erp.databinding.ActivityPdfPreviewBinding
import com.zbcz.erp.util.DensityUtils
import com.zbcz.erp.util.onSingleClick
import com.zbcz.erp.viewmodel.PdfPreViewViewModel
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException

class PdfPreViewActivity : BaseActivity() {

    private var pdfRenderer: PdfRenderer? = null
    private var currentPage: PdfRenderer.Page? = null
    private var parcelFileDescriptor: ParcelFileDescriptor? = null

    companion object {
        const val REMOTE_URL = "remote_pdf_url"
        const val LOCAL_URL = "local_url"
    }

    private lateinit var mBinding: ActivityPdfPreviewBinding

    private val mViewModel: PdfPreViewViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        mBinding = ActivityPdfPreviewBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        init()
        super.onCreate(savedInstanceState)
    }

    private var mPage = 0

    fun init() {
        mBinding.clParent.setPadding(
            0, DensityUtils.dp2px(this, 48f), 0, 0
        )
        mBinding.clTitle.ivCommonBack.onSingleClick {
            finish()
        }
        val remoteUrl = intent?.getStringExtra(REMOTE_URL)
        val localUrl = intent?.getStringExtra(LOCAL_URL)
        if (remoteUrl != null) {
            val fileName = remoteUrl.substringAfterLast("/")
            mViewModel.downloadPdfFile(remoteUrl, fileName)
            mViewModel.fileDownloadedLiveData.observe(this) { pdfFile ->
                pdfFile?.let {
                    openRenderer(it)
                    showPage(pageIndex)
                }
            }
        } else if (localUrl != null) {
            val uri = Uri.parse(localUrl)
            lifecycleScope.launch {
                val file = mViewModel.copyUriToFile(uri)
                file?.let {
                    openRenderer(it)
                    showPage(pageIndex)
                }
            }
        }
        mBinding.ivNext.onSingleClick {
            nextPage()
        }
        mBinding.ivPre.onSingleClick {
            previousPage()
        }
    }

    var pageIndex = 0

    private fun nextPage() {
        val currentIndex = pageIndex
        val pageCount = pdfRenderer?.pageCount ?: return

        if (currentIndex < pageCount - 1) {
            pageIndex++
            showPage(pageIndex)
        }
    }

    private fun previousPage() {
        val currentIndex = pageIndex

        if (currentIndex > 0) {
            pageIndex--
            showPage(pageIndex)
        }
    }

    @Throws(IOException::class)
    private fun openRenderer(file: File) {
        parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
        pdfRenderer = PdfRenderer(parcelFileDescriptor!!)
    }

    @Throws(IOException::class)
    private fun closeRenderer() {
        currentPage?.close()
        pdfRenderer?.close()
        parcelFileDescriptor?.close()
    }

    private fun showPage(index: Int) {
        pdfRenderer?.let { renderer ->
            if (renderer.pageCount <= index) return
            currentPage?.close()
            currentPage = renderer.openPage(index).also { page ->
                val bitmap = Bitmap.createBitmap(page.width, page.height, Bitmap.Config.ARGB_8888)
                page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
                mBinding.pdfImageView.setImageBitmap(bitmap)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            closeRenderer()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}